package com.zhentao.appointment.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.appointment.dto.AppointmentNoticeDTO;
import com.zhentao.appointment.request.AppointmentNoticeRequest;
import com.zhentao.pojo.AppointmentNotices;
import com.zhentao.pojo.R;
import com.zhentao.service.AppointmentNoticesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预约须知管理控制器
 *
 * @author zhentao
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/appointment-notice")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AppointmentNoticeController {

    @Autowired
    private AppointmentNoticesService appointmentNoticesService;

    /**
     * 分页查询预约须知列表
     */
    @GetMapping("/list")
    public R<IPage<AppointmentNoticeDTO>> getNoticeList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String noticeTitle,
            @RequestParam(required = false) String noticeType) {
        
        log.info("分页查询预约须知列表，当前页：{}，每页大小：{}，标题：{}，类型：{}", current, size, noticeTitle, noticeType);
        
        try {
            Page<AppointmentNotices> page = new Page<>(current, size);
            LambdaQueryWrapper<AppointmentNotices> wrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (noticeTitle != null && !noticeTitle.trim().isEmpty()) {
                wrapper.like(AppointmentNotices::getNoticeTitle, noticeTitle.trim());
            }
            if (noticeType != null && !noticeType.trim().isEmpty()) {
                wrapper.eq(AppointmentNotices::getNoticeType, noticeType.trim());
            }
            
            // 按排序顺序和创建时间排序
            wrapper.orderByAsc(AppointmentNotices::getSortOrder)
                   .orderByDesc(AppointmentNotices::getCreateTime);
            
            IPage<AppointmentNotices> result = appointmentNoticesService.page(page, wrapper);
            
            // 转换为DTO
            IPage<AppointmentNoticeDTO> dtoPage = new Page<>(current, size, result.getTotal());
            List<AppointmentNoticeDTO> dtoList = result.getRecords().stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            dtoPage.setRecords(dtoList);
            
            log.info("分页查询预约须知列表成功，总数：{}", result.getTotal());
            return R.ok(dtoPage);
            
        } catch (Exception e) {
            log.error("分页查询预约须知列表失败", e);
            return R.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有启用的预约须知（用于前端展示）
     */
    @GetMapping("/all")
    public R<List<AppointmentNoticeDTO>> getAllNotices() {
        log.info("获取所有启用的预约须知");
        
        try {
            LambdaQueryWrapper<AppointmentNotices> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AppointmentNotices::getStatus, 1) // 只查询启用的
                   .orderByAsc(AppointmentNotices::getSortOrder)
                   .orderByDesc(AppointmentNotices::getCreateTime);
            
            List<AppointmentNotices> notices = appointmentNoticesService.list(wrapper);
            List<AppointmentNoticeDTO> dtoList = notices.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            
            log.info("获取所有启用的预约须知成功，数量：{}", dtoList.size());
            return R.ok(dtoList);
            
        } catch (Exception e) {
            log.error("获取所有启用的预约须知失败", e);
            return R.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询预约须知详情
     */
    @GetMapping("/{id}")
    public R<AppointmentNoticeDTO> getNoticeById(@PathVariable Long id) {
        log.info("根据ID查询预约须知详情，ID：{}", id);
        
        try {
            AppointmentNotices notice = appointmentNoticesService.getById(id);
            if (notice == null) {
                return R.error("预约须知不存在");
            }
            
            AppointmentNoticeDTO dto = convertToDTO(notice);
            log.info("根据ID查询预约须知详情成功");
            return R.ok(dto);
            
        } catch (Exception e) {
            log.error("根据ID查询预约须知详情失败，ID：{}", id, e);
            return R.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增预约须知
     */
    @PostMapping("/add")
    public R<String> addNotice(@Valid @RequestBody AppointmentNoticeRequest request) {
        log.info("新增预约须知，请求参数：{}", request);
        
        try {
            AppointmentNotices notice = new AppointmentNotices();
            BeanUtils.copyProperties(request, notice);
            notice.setCreateTime(LocalDateTime.now());
            notice.setUpdateTime(LocalDateTime.now());
            
            boolean success = appointmentNoticesService.save(notice);
            if (success) {
                log.info("新增预约须知成功，ID：{}", notice.getId());
                return R.ok("新增成功");
            } else {
                return R.error("新增失败");
            }
            
        } catch (Exception e) {
            log.error("新增预约须知失败", e);
            return R.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 更新预约须知
     */
    @PutMapping("/{id}")
    public R<String> updateNotice(@PathVariable Long id, @Valid @RequestBody AppointmentNoticeRequest request) {
        log.info("更新预约须知，ID：{}，请求参数：{}", id, request);
        
        try {
            AppointmentNotices existingNotice = appointmentNoticesService.getById(id);
            if (existingNotice == null) {
                return R.error("预约须知不存在");
            }
            
            AppointmentNotices notice = new AppointmentNotices();
            BeanUtils.copyProperties(request, notice);
            notice.setId(id);
            notice.setUpdateTime(LocalDateTime.now());
            
            boolean success = appointmentNoticesService.updateById(notice);
            if (success) {
                log.info("更新预约须知成功，ID：{}", id);
                return R.ok("更新成功");
            } else {
                return R.error("更新失败");
            }
            
        } catch (Exception e) {
            log.error("更新预约须知失败，ID：{}", id, e);
            return R.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除预约须知（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public R<String> deleteNotice(@PathVariable Long id) {
        log.info("删除预约须知，ID：{}", id);
        
        try {
            boolean success = appointmentNoticesService.removeById(id);
            if (success) {
                log.info("删除预约须知成功，ID：{}", id);
                return R.ok("删除成功");
            } else {
                return R.error("删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除预约须知失败，ID：{}", id, e);
            return R.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除预约须知
     */
    @DeleteMapping("/batch")
    public R<String> batchDeleteNotices(@RequestBody List<Long> ids) {
        log.info("批量删除预约须知，ID列表：{}", ids);
        
        try {
            boolean success = appointmentNoticesService.removeByIds(ids);
            if (success) {
                log.info("批量删除预约须知成功，数量：{}", ids.size());
                return R.ok("批量删除成功");
            } else {
                return R.error("批量删除失败");
            }
            
        } catch (Exception e) {
            log.error("批量删除预约须知失败", e);
            return R.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 更新预约须知状态
     */
    @PutMapping("/{id}/status")
    public R<String> updateNoticeStatus(@PathVariable Long id, @RequestParam Integer status) {
        log.info("更新预约须知状态，ID：{}，状态：{}", id, status);
        
        try {
            AppointmentNotices notice = new AppointmentNotices();
            notice.setId(id);
            notice.setStatus(status);
            notice.setUpdateTime(LocalDateTime.now());
            
            boolean success = appointmentNoticesService.updateById(notice);
            if (success) {
                log.info("更新预约须知状态成功，ID：{}，状态：{}", id, status);
                return R.ok("状态更新成功");
            } else {
                return R.error("状态更新失败");
            }
            
        } catch (Exception e) {
            log.error("更新预约须知状态失败，ID：{}", id, e);
            return R.error("状态更新失败：" + e.getMessage());
        }
    }

    /**
     * 转换为DTO
     */
    private AppointmentNoticeDTO convertToDTO(AppointmentNotices notice) {
        AppointmentNoticeDTO dto = new AppointmentNoticeDTO();
        BeanUtils.copyProperties(notice, dto);
        
        // 设置类型描述
        switch (notice.getNoticeType()) {
            case "general":
                dto.setNoticeTypeDesc("一般须知");
                break;
            case "policy":
                dto.setNoticeTypeDesc("政策须知");
                break;
            case "requirement":
                dto.setNoticeTypeDesc("要求须知");
                break;
            default:
                dto.setNoticeTypeDesc("未知类型");
        }
        
        // 设置状态描述
        dto.setStatusDesc(notice.getStatus() == 1 ? "启用" : "禁用");
        
        return dto;
    }
}
